#define _CRT_SECURE_NO_WARNINGS 1
#include"Polynomial_summation.h"

void creatploynomial(oper*P)
{
	P = (oper*)malloc(sizeof(oper));
	P->next = NULL;
}

void readoperands(oper* P,int input)
{
	oper* tmp = P;
	while (input)
	{
		tmp->next = (oper*)malloc(sizeof(oper));
		tmp = tmp->next;
		scanf("%d   %d", &tmp->coe, &tmp->exp);
		tmp->next = NULL;
		input--;
	}
}

void swapoperands(oper*s,oper*l)
{
	int c = 0;
	int e = 0;
	c = s->coe;
	s->coe = l->coe;
	l->coe = c;
	e = s->exp;
	s->exp = l->exp;
	l->exp = e;
}

void sortpolynomial(oper*P)
{
	oper* tmp = P;
	tmp = tmp->next;
	oper* sum = tmp;
	oper* stop = NULL;
	while (sum != stop)
	{
		tmp = sum;
		oper* fore = tmp->next;
		while (fore != stop)
		{
			if (tmp->exp < fore->exp)
			{
				swapoperands(tmp, fore);
			}
			tmp = tmp->next;
			fore = fore->next;
		}
		stop = tmp;
	}
}

int my_pow(int x, int exp)
{
	int i = 0;
	int ret = 1;
	for (i = 0; i < exp; i++)
	{
		ret *= x;
	}
	return ret;
}


void printsummation_x(oper* P,int x)
{
	oper* tmp = P;
	tmp = tmp->next;

	while (tmp != NULL)
	{
		printf("%d%d^%d", tmp->coe,x, tmp->exp);
		if (tmp->next != NULL)
		{
			printf(" + ");
		}
		tmp = tmp->next;
	}
	printf("=");
}


int addoperands(oper* P, int x)
{
	printsummation_x(P, x);
	int j = 0;
	oper* tmp = P;
	tmp = tmp->next;
	while (tmp != NULL)
	{
		j += (tmp->coe * my_pow(x, tmp->exp));
		tmp = tmp->next;
	}
	return j;
}

void printsummation(oper*P)
{
	oper* tmp = P;
	tmp = tmp->next;
	
	while (tmp != NULL)
	{
		printf("%dx^%d", tmp->coe, tmp->exp);
		if (tmp->next != NULL)
		{
			printf(" + ");
		}
		tmp = tmp->next;
	}
	printf("\n");
}